package com.gxa.pojo.entity.tjgl.util;

import lombok.Getter;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;

/**
 * parse "yyyy-MM-dd"||"yyyy-MM"||"yyyy" to a legal date
 * do not allow null(otherwise throw null pointer exception)
 * use @RequestParam() to set a default value like ""
 * @author IKE <hp1041735092@outlook.jp>
 * @date 26/2/2024
 */
@Getter
public class DateInfo {
    private final Integer year;
    private final Integer month;
    private final Integer day;

    public DateInfo(int year) {
        this.year = year;
        this.month = null;
        this.day = null;
    }

    public DateInfo(int year, int month) {
        this.year = year;
        this.month = month;
        this.day = null;
    }

    public DateInfo(LocalDate localDate) {
        this.year = localDate.getYear();
        this.month = localDate.getMonthValue();
        this.day = localDate.getDayOfMonth();
    }

    public static final DateTimeFormatter YEAR_FORMATTER = DateTimeFormatter.ofPattern("yyyy");
    public static final DateTimeFormatter YEAR_MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM");
    public static final DateTimeFormatter YEAR_MONTH_DAY_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static DateInfo fromString(String date) {
        try {
                TemporalAccessor ta = YEAR_FORMATTER.parse(date);
                return new DateInfo(ta.get(ChronoField.YEAR));
            } catch (DateTimeParseException ignored) {
            try {
                    TemporalAccessor ta = YEAR_MONTH_FORMATTER.parse(date);
                    return new DateInfo(ta.get(ChronoField.YEAR), ta.get(ChronoField.MONTH_OF_YEAR));
                } catch (DateTimeParseException ignored2) {
                try {
                        LocalDate localDate = LocalDate.parse(date, YEAR_MONTH_DAY_FORMATTER);
                        return new DateInfo(localDate.getYear(), localDate.getMonthValue(), localDate.getDayOfMonth());
                    } catch (DateTimeParseException e) {
                        return new DateInfo(LocalDate.now().getYear()); //if illegal -> default:return current year
                    }
            }
        }
    }

    public DateInfo(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

}